﻿using Afdian.Sdk;
using Afdian.Sdk.ResponseModels;
using KinonekoSoftware.CodariaDB.Presets;
using KinonekoSoftware.JuXiaoYouDB.Core;
using KinonekoSoftware.Studio.Models.Shells;
using KinonekoSoftware.Studio.Models.Shells;
using KinonekoSoftware.Studio.Resources.Converters;
using KinonekoSoftware.UI;

namespace KinonekoSoftware.Studio.ViewModels
{
    public sealed partial class SettingViewModel : RepositoryGalleryItem
    {
        private static readonly DataMode[]   Option_DataMode = new[] { DataMode.Release, DataMode.Protected };
        private static readonly Theme[]      Option_Theme    = new[] { Theme.Dark, Theme.Light };
        private const           string       Afdian_Token    = "nhRretPBfKWsa58vMq3Hjmu4GxYcp7gF";
        private const           string       Afdian_UserID   = "92cc8112da9411ecb52152540025c377";
        private readonly        AfdianClient _client;


        private readonly Dictionary<Preset_Avatar, object> _PresetAvatar;
        private readonly Dictionary<Preset_Icon, object>   _PresetIcon;
        private readonly JuXiaoYouSetting                  _setting_app;
        private readonly ForestSetting                     _setting_ui;
        private readonly RepositorySetting                 _setting_repo;
        private readonly IRepository                       _repository;

        private readonly string _version_arch;
        private readonly string _version_app;
        private readonly string _version_app_inside;


        public SettingViewModel()
        {
            var app = Ioc.Get<AppViewModel>();

            _client             = new AfdianClient(Afdian_UserID, Afdian_Token);
            _version_arch       = app.LaunchContext.ArchitectureVersion;
            _version_app        = app.LaunchContext.ApplicationVersion;
            _version_app_inside = app.LaunchContext.ApplicationInsideVersion;

            _setting_app  = Ioc.Get<JuXiaoYouSetting>();
            _setting_ui   = Ioc.Get<ForestSetting>();
            _setting_repo = Ioc.Get<RepositorySetting>();
            _repository   = Platform.GetRepository();
            Repositories  = new ObservableCollection<RepositoryCache>();
            Licenses      = new ObservableCollection<OpenSourceLicense>();
            Sponsors      = new ObservableCollection<QuerySponsorResponseModel.DataModel.ListItemModel.UserModel>();

            _PresetAvatar = new Dictionary<Preset_Avatar, object>();
            _PresetIcon   = new Dictionary<Preset_Icon, object>();

            SaveSettingCommand = CreateCommand(DoSaveSettingCommand);

            EnableViewCache = false;
        }

        //-------------------------------------------------
        //
        //          Command Handlers
        //
        //-------------------------------------------------
        protected override void OnStart()
        {
            Repositories.AddMany(_setting_repo.Repositories, true);

            //
            // 获取赞助列表
            Task.Run(async () =>
            {
                Xplat.RunOnUIThread(() =>
                {
                    SponsorDownloading       = true;
                    SponsorDownloadCompleted = false;
                    SponsorDownloadText      = "正在加载赞助列表....";
                });

                var sponsor = await _client.QuerySponsorModelAsync();

                if (sponsor.ec == 200)
                {
                    Xplat.RunOnUIThread(() =>
                    {
                        SponsorDownloading       = false;
                        SponsorDownloadCompleted = true;
                        Sponsors.Clear();

                        foreach (var model in sponsor.data.list)
                        {
                            Sponsors.Add(model.user);
                        }
                    });
                }
                else
                {
                    Xplat.RunOnUIThread(() =>
                    {
                        SponsorDownloading       = true;
                        SponsorDownloadCompleted = false;
                        SponsorDownloadText      = "加载赞助列表失败";
                    });
                }
            });

            //
            //
            InitializeLicenses();
            
            //
            //
            base.OnStart();
        }



        protected override void OnResume()
        {
            Repositories.AddMany(_setting_repo.Repositories, true);
            base.OnResume();
        }

        //-------------------------------------------------
        //
        //          Command Handlers
        //
        //-------------------------------------------------
        private async void DoSaveSettingCommand()
        {
            await Platform.SaveSetting(Setting_UI);
            await Platform.SaveSetting(Setting_App);
            await Success(TitleSR.SuccessOperation, TextSR.Successful_Save);
        }

        #region Licenses

        private static OpenSourceLicense License(string name, string url, string license)
        {
            return new OpenSourceLicense
            {
                ProjectName    = name,
                ProjectUrl     = url,
                ProjectLicense = license,
            };
        }

        private void InitializeLicenses()
        {
            const string BSD3L   = "BSD 3-Clause License";
            const string Apache2 = "Apache-2.0 license";
            const string MIT     = "MIT";
            
            Licenses.Add(License("DryIoc.dll", "https://github.com/dadhi/DryIoc", MIT));
            Licenses.Add(License("QuikGraph", "https://github.com/KeRNeLith/QuikGraph", "MS-PL"));
            Licenses.Add(License("SixLabors.ImageSharp", "https://github.com/SixLabors/ImageSharp", "Six Labors Split License"));
            Licenses.Add(License("Ookii.Dialogs.Wpf", "https://github.com/ookii-dialogs/ookii-dialogs-wpf", BSD3L));
            Licenses.Add(License("gong-wpf-dragdrop", "https://github.com/punker76/gong-wpf-dragdrop", BSD3L));
            Licenses.Add(License("NLog", "https://github.com/NLog/NLog", BSD3L));
            Licenses.Add(License("MediatR", "https://github.com/jbogard/MediatR", Apache2));
            Licenses.Add(License("SharpZipLib", "https://github.com/icsharpcode/SharpZipLib", MIT));
            Licenses.Add(License("System.Reactive", "https://github.com/dotnet/dotnet", MIT));
            Licenses.Add(License("System.IO.Hashing", "https://github.com/dotnet/dotnet", MIT));
            Licenses.Add(License("Microsoft.Xaml.Behaviors.Wpf", "https://github.com/dotnet/dotnet", MIT));
            Licenses.Add(License("Microsoft.Extensions.ObjectPool", "https://github.com/dotnet/dotnet", MIT));
            Licenses.Add(License("JetBrains.Annotations", "https://github.com/JetBrains/JetBrains.Annotations", MIT));
            
            //
            //
            Licenses.Add(License("Avalonia", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.Android", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.iOS", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.Fonts.Inter", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.ReactiveUI", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.Themes.Fluent", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.Desktop", "https://github.com/AvaloniaUI/Avalonia", MIT));
            Licenses.Add(License("Avalonia.Xaml.Interactivity", "https://github.com/AvaloniaUI/Avalonia", MIT));
            
            //
            //
            Licenses.Add(License("Xamarin.AndroidX.Core.SplashScreen", "https://github.com/xamarin/AndroidX", MIT));
        }

        #endregion

        #region Sponsor

        private bool   _sponsorDownloadCompleted;
        private bool   _sponsorDownloading;
        private int    _totalSponsorPageCount;
        private string _sponsorDownloadText;

        public ObservableCollection<QuerySponsorResponseModel.DataModel.ListItemModel.UserModel> Sponsors { get; }

        public string SponsorDownloadText
        {
            get => _sponsorDownloadText;
            set => SetValue(ref _sponsorDownloadText, value);
        }

        public int TotalSponsorPageCount
        {
            get => _totalSponsorPageCount;
            set => SetValue(ref _totalSponsorPageCount, value);
        }

        public bool SponsorDownloading
        {
            get => _sponsorDownloading;
            set => SetValue(ref _sponsorDownloading, value);
        }

        public bool SponsorDownloadCompleted
        {
            get => _sponsorDownloadCompleted;
            set => SetValue(ref _sponsorDownloadCompleted, value);
        }

        #endregion

        //-------------------------------------------------
        //
        //          Command Handlers
        //
        //-------------------------------------------------
        public Preset_Icon Icon_Preset
        {
            get => _setting_app.Preset_Icon;
            set => _setting_app.Preset_Icon = value;
        }

        public Preset_Avatar Avatar_Preset
        {
            get => _setting_app.Preset_Avatar;
            set => _setting_app.Preset_Avatar = value;
        }


        public ObservableCollection<RepositoryCache>    Repositories { get; }
        public ObservableCollection<OpenSourceLicense>  Licenses     { get; }
        public ObservableCollection<IDispoableDatabase> Databases    => Platform.ObservableDatabaseCollection;

        public ICommandEX SaveSettingCommand { get; }

        public string           ArchitectureVersion      => _version_arch;
        public string           ApplicationVersion       => _version_app;
        public string           ApplicationInsideVersion => _version_app_inside;
        public ForestSetting    Setting_UI               => _setting_ui;
        public JuXiaoYouSetting Setting_App              => _setting_app;
        public IRepository      Repository               => _repository;
    }
}